const jwt = require('jsonwebtoken');
const { getRes } = require('../res')
function checkToekn(token) {
    return new Promise(function(resolve, reject) {
        jwt.verify(token, 'qi_secret_sheng', function(err, decoded) {
            if(err) reject(err)
            else resolve(decoded);
        });
    });
}

module.exports = async (ctx,next) => {//中间件测试，用来控制API鉴权,hooks等
    console.log('i have come in the token middleware.....................');
    let url = ctx.request.url;
    let token = ctx.request.body.token
    if(url.indexOf("/api/user/register_toke")==0){
        token = url.slice("/api/user/register_toke?token=".length);
    }
    console.log(token);
    try{
        let res = await checkToekn(token);
        console.log('.......veryifying token.......');
        console.log(res);
        if(res.pwd==null){
            ctx.user = res;
        }else{
            ctx.register = res;
        }
        await next();
    }catch(e){
        if(url.indexOf("/api/user/register_toke")==0){
            ctx.response.body = getRes(3);
        }else{
            console.log(e);
            ctx.response.body = getRes(400,e);
        }
    }
};